cloneObject = function(obj) { // fails on Date object
	var o = new Object();
	for ( var property in obj) {
		o[property] = (typeof (obj[property]) == 'object') ? cloneObject(obj[property]) : obj[property];
	}
	return o;
	//return jQuery.extend(true, {}, obj); // jQuery already does it
};

function cloneTask(t) { // complete proper copy of task
	var c = jQuery.extend(true, {}, t);
	if (t.dueDate) c.dueDate = t.dueDate.clone();
	if (t.completedDate) c.completedDate = t.completedDate.clone();
	if (t.addedDate) c.addedDate = t.addedDate.clone();
	if (t.lastModified) c.lastModified = t.lastModified.clone();
	//if (t.freq[1] && t.freq[0] != 'r') c.freq[1] = t.freq[1].clone();
	return c;
}

function reviveTask(newtask_deser) {	// revive task object
	var newtask = jQuery.extend(true, (new task()), newtask_deser);
	// revive Date objects
	newtask.addedDate = reviveDateJSON(newtask.addedDate);
	newtask.completedDate = reviveDateJSON(newtask.completedDate);
	newtask.dueDate = reviveDateJSON(newtask.dueDate);
	newtask.lastModified = reviveDateJSON(newtask.lastModified);
	//if (newtask.freq[1] && newtask.freq[0] != 'r')
	//	newtask.freq[1] = reviveDateJSON(newtask.freq[1]);
	return newtask;
}

cloneArray = function(arr) {
	var a = new Array();
	for ( var property in arr) {
		a[property] = arr[property]; 
	}
	return a;
};

// fn(acc, item) 
function accumulate(start, arr, fn) {
	var acc = start;
	for ( var i in arr)
		acc = fn(acc, arr[i]);
	
	return acc;
};

function participantNameById(pid) {
	
	if(pid == wave.getViewer().getId())
		return "You";
		
	var p = wave.getParticipantById(pid);
	
	return (p != null) ? p.getDisplayName() : "Unknown";
	
}


function nullOrEmpty(arr){
	return arr == null || arr.length == 0;
}

function randStr(l) {
  var pass = '', chars = 'abcdefghijklmnopqrstuvwxyz';
  for (var x = 0; x < l; x++)
    pass += chars[Math.floor(Math.random() * 26)];
  return pass;
}

function arrToHumanStr(arr){
	
	if(nullOrEmpty(arr))
		return "";
	
	var str = arr[0];
	for ( var i = 1; i < arr.length-1; i++)
		str += ", " + arr[i];

	if(arr.length > 1)
		str += " and " + arr[arr.length-1];
	
	return str;
}

/*
 * Add 's' to type, if plural
 * example: humanCount('car', 2) = '2 cars'
 */
function humanCount(type, number){
	
	if(number < 2)
		return number + " " + type;
	
	return number + " " + type + "s";
	
}

// Date object .toJSON ISO 8601 string with UTC correct time.
Date.prototype.toJSON = function (key) {
  function f(n) { return n < 10 ? '0' + n : n; }
  return this.getUTCFullYear()   + '-' +
       f(this.getUTCMonth() + 1) + '-' +
       f(this.getUTCDate())      + 'T' +
       f(this.getUTCHours())     + ':' +
       f(this.getUTCMinutes())   + ':' +
       f(this.getUTCSeconds())   + 'Z';
};

// Restore Date object from ISO 8601 JSON.stringify or .toJSON. (date.js fails)
function reviveDateJSON(value) {
	if (typeof value === 'string') {
	var a =
	/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
	if (a) return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));
	}
	return value;
}

function dateDiff(d1,d2,ti) { // is |(d1-d2)|<ti ? ('almost equal')
	var diff = (d1-d2);
	if (diff > -ti && diff < ti) return true;
	return false;
}

// Compares arrays, non recursive into objects/arrays, for use in task compare.
// Warning: do not .prototype -- breaks iteration (for i in a)
// TODO: better array compare?
compareArrays = function(ar1,ar2) {
	if (ar1.length != ar2.length) return false;
	for (var i = 0; i < ar1.length; i++) {
		if (ar1[i] !== ar2[i]) return false;
	}
	return true;
};

// Compares tasks, returns count of nonequal data properties.
function compareTasks(t1,t2) { 
	var cn = 0;
	for (var p in t1) {
		if (typeof t1[p] === 'function') continue;
		if (jQuery.isArray(t1[p]) && compareArrays(t1[p], t2[p])) continue;
		if ((p == 'dueDate' || p == 'addedDate' || p == 'completedDate')
			&& t1[p] && t2[p] && dateDiff(t1[p],t2[p],1000)) continue;
		if (t1[p] != t2[p]) cn++;
	}
	return cn;
}

// QuickAdd task to Google Calendar
function gcalQuickAdd(t) {
	var s = '' + t.title;
	if (t.location) s += " at " + t.location + "";
	if (t.dueDate) s += " on " + t.dueDate.toString('yyyy/M/d HH:mm') + "";
	
	void(
		// open a new window with this information in Google Calendar.
    window.open(
      encodeURI('http://www.google.com/calendar/event?ctext='+s+
			'&action=TEMPLATE&pprop=HowCreated:QUICKADD')
      ,'addwindow'
      //,'status=no,toolbar=no,width=520,height=470,resizable=yes'
    )
	);
}

/**
 * JQuery SpecialKeys plugin
 * You can use this plugin to determine if any special keys are 
 * pressed within any of you Javascript code.
 * 
 * @author Amjad Mohamed
 * @version 0.1
 * 
 */

(function($) {
	
	var pressed = {};
	var keyshort = {
		'ctrl': 17,
		'control': 17,
		'alt': 18,
		'shift': 16,
		'enter': 13,
		'return': 13
	};
	
	jQuery.specialKeys = function(key) {
		key = $.trim(key).toLowerCase();
		
		if (keyshort[key] != undefined) {
			return pressed[keyshort[key]];
		} else {
			return pressed[key];
		}
	};

	$(document).bind('keydown', function(e) {
		pressed[e.keyCode] = true;
	});

	$(document).bind('keyup', function(e) {
		delete pressed[e.keyCode];
	});

})(jQuery);


/*
 * timeago: a jQuery plugin, version: 0.8.0 (2009-10-25)
 * @requires jQuery v1.2.3 or later
 *
 * Timeago is a jQuery plugin that makes it easy to support automatically
 * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
 *
 * For usage and examples, visit:
 * http://timeago.yarp.com/
 *
 * Licensed under the MIT:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2008-2009, Ryan McGeary (ryanonjavascript -[at]- mcgeary [*dot*] org)
 */
(function($) {
  $.timeago = function(timestamp) {
    if (timestamp instanceof Date) return inWords(timestamp);
    else if (typeof timestamp == "string") return inWords($.timeago.parse(timestamp));
    else return inWords($.timeago.datetime(timestamp));
  };
  var $t = $.timeago;

  $.extend($.timeago, {
    settings: {
      refreshMillis: 60000,
      allowFuture: false,
      strings: {
        prefixAgo: null,
        prefixFromNow: null,
        suffixAgo: "ago",
        suffixFromNow: "from now",
        ago: null, // DEPRECATED, use suffixAgo
        fromNow: null, // DEPRECATED, use suffixFromNow
        seconds: "less than a minute",
        minute: "about a minute",
        minutes: "%d minutes",
        hour: "about an hour",
        hours: "about %d hours",
        day: "a day",
        days: "%d days",
        month: "about a month",
        months: "%d months",
        year: "about a year",
        years: "%d years"
      }
    },
    inWords: function(distanceMillis) {
      var $l = this.settings.strings;
      var prefix = $l.prefixAgo;
      var suffix = $l.suffixAgo || $l.ago;
      if (this.settings.allowFuture) {
        if (distanceMillis < 0) {
          prefix = $l.prefixFromNow;
          suffix = $l.suffixFromNow || $l.fromNow;
        }
        distanceMillis = Math.abs(distanceMillis);
      }

      var seconds = distanceMillis / 1000;
      var minutes = seconds / 60;
      var hours = minutes / 60;
      var days = hours / 24;
      var years = days / 365;

      var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
        seconds < 90 && substitute($l.minute, 1) ||
        minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
        minutes < 90 && substitute($l.hour, 1) ||
        hours < 24 && substitute($l.hours, Math.round(hours)) ||
        hours < 48 && substitute($l.day, 1) ||
        days < 30 && substitute($l.days, Math.floor(days)) ||
        days < 60 && substitute($l.month, 1) ||
        days < 365 && substitute($l.months, Math.floor(days / 30)) ||
        years < 2 && substitute($l.year, 1) ||
        substitute($l.years, Math.floor(years));

      return $.trim([prefix, words, suffix].join(" "));
    },
    parse: function(iso8601) {
      var s = $.trim(iso8601);
      s = s.replace(/-/,"/").replace(/-/,"/");
      s = s.replace(/T/," ").replace(/Z/," UTC");
      s = s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
      return new Date(s);
    },
    datetime: function(elem) {
      var iso8601 = $(elem).is('time') ? $(elem).attr('datetime') : $(elem).attr('title');
      return $t.parse(iso8601);
    }
  });

  $.fn.timeago = function() {
    var self = this;
    self.each(refresh);

    var $s = $t.settings;
    if ($s.refreshMillis > 0) {
      setInterval(function() { self.each(refresh); }, $s.refreshMillis);
    }
    return self;
  };

  function refresh() {
    var data = prepareData(this);
    if (!isNaN(data.datetime)) {
      $(this).text(inWords(data.datetime));
    }
    return this;
  }

  function prepareData(element) {
    element = $(element);
    if (element.data("timeago") === undefined) {
      element.data("timeago", { datetime: $t.datetime(element) });
      var text = $.trim(element.text());
      if (text.length > 0) element.attr("title", text);
    }
    return element.data("timeago");
  }

  function inWords(date) {
    return $t.inWords(distance(date));
  }

  function distance(date) {
    return (new Date().getTime() - date.getTime());
  }

  function substitute(stringOrFunction, value) {
    var string = $.isFunction(stringOrFunction) ? stringOrFunction(value) : stringOrFunction;
    return string.replace(/%d/i, value);
  }

  // fix for IE6 suckage
  document.createElement('abbr');
  document.createElement('time');
})(jQuery);
